import json
import zipfile
import numpy as np
import re
import os

from txt_parser import parse_text_knowlege
from utlis import gen_str_codes
from file_encryptor import encryptor
import threading
g_img_lock = threading.Lock()



IMAGE_PATTERN = r'([^\s()]+?\.(?:jpg|jpeg|png|gif|bmp|svg|webp|tiff|heic|avif))'

def detect_images(file, source_type='docx', valid_extensions=['.png', '.jpg', '.jpeg']):
    if source_type=='docx':
        with zipfile.ZipFile(file, 'r') as zip_ref:
            image_files = [file_info for file_info in zip_ref.infolist()
                           if file_info.filename.startswith('word/media/') and
                           any(file_info.filename.endswith(ext) for ext in valid_extensions)]
    else:
        pass
    return image_files


def image_summary_url(line, call_llm=None, llm_histories=None, local_llm_name=None, local_llm=None, local_llm_tz=None, model_config=None, local_summary=False):
    image_summary = ''
    match = re.search(IMAGE_PATTERN, line, re.IGNORECASE)
    if match:
        image_url = match.group(1)
        # ****UNDER_DEVELOPMENT****, get the image via the url, parse its contents and generate the summary
        if image_summary.strip()=='':
            image_summary = image_url
        else:
            image_summary = image_summary + '-->' + image_url
    return image_summary


def replace_and_add_back(s):
    new_s = ""
    i = 0
    while i < len(s):
        if s[i:i+2] == '\\\\':
            new_s += '\\\\'  # Add back "\\" for the replaced "\\\\"
            i += 2
        else:
            new_s += s[i]
            i += 1      
    return new_s


def parse_image(img_obj, image_path, know_title=None, call_llm=None, llm_histories=[], KB_PATH=None, kb_dir=None):
    img_root = kb_dir
    failed_lst = []
    json_know = {}
    os.makedirs(img_root, exist_ok=True)
    try:
        # img_recog_content = '' # UNDER DEVELOPMENT using LVM to extract content
        img_extension = os.path.splitext(image_path)[-1]
        img_id = 'IMAGE_UPLOAD_' + gen_str_codes(know_title + str(np.random.rand())) + '_UPLOAD_IMAGE'
        if encryptor.encrypt:
            encryptor.save_to_file(img_obj.read(), os.path.join(img_root, know_title+img_extension))
        else:
            img_obj.save(os.path.join(img_root, know_title+img_extension))        

    except Exception as e:
        failed_lst.append(image_path)
        print('\t', e, '\n\tsaving image fails, maybe check if the title is correctly input...')
    
    # try:
    #     orc_res = requests.post("https://api.mathpix.com/v3/text",
    #         files={"file": open(image_path,"rb")},
    #         data={
    #           "options_json": json.dumps({
    #             "math_inline_delimiters": ["$", "$"],
    #             "rm_spaces": True
    #           })
    #         },
    #         headers={
    #             "app_id": "checkerboard_414411_52c5c3",
    #             "app_key": "18ad0d6b3b3fc5da9a1a46fa0501bf331d340bba2410cee7b52f732321a90b01"
    #         }
    #     )
        
    #     orc_res = orc_res.json()['text']
    # except Exception as e:
    #     orc_res = ''
    #     print('\tparsing image fails because ', e)

    # if len(orc_res)<10:
    #     img_text = img_recog_content # *****UNDER DEVELOPMENT*****
    # else:
    #     img_text = replace_and_add_back(orc_res) + '\n' + img_recog_content

    with g_img_lock:
        img_record_pth = os.path.join(img_root, 'image_record.json')
        img_record = {}
        if os.path.exists(img_record_pth):
            if encryptor.encrypt:
                img_record = encryptor.load_from_file(img_record_pth)
            else:
                with open(img_record_pth, 'r', encoding='utf-8') as f:
                    img_record = json.load(f)
        img_record.update({img_id : know_title + img_extension})
        if encryptor.encrypt:
            encryptor.save_to_file(img_record, img_record_pth)
        else:
            with open(img_record_pth, 'w', encoding='utf-8') as f:
                json.dump(img_record, f, ensure_ascii=False, indent=4)
        
        img_label_pth = os.path.join(img_root, 'image_label.json')
        img_label = {}
        if os.path.exists(img_label_pth):
            if encryptor.encrypt:
                img_label = encryptor.load_from_file(img_label_pth)
            else:
                with open(img_label_pth, 'r', encoding='utf-8') as f:
                    img_label = json.load(f)
        img_label.update({know_title + img_extension : [know_title]})
        if encryptor.encrypt:
            encryptor.save_to_file(img_label, img_label_pth)
        else:
            with open(img_label_pth, 'w', encoding='utf-8') as f:
                json.dump(img_label, f, ensure_ascii=False, indent=4)
    return json_know, failed_lst


if __name__ == "__main__":
    import os
    KB_PATH = '../知识固化库_Eric'
    image_path = os.path.join(KB_PATH, '建设施工技术知识/市政绿化工程施工组织/市政绿化工程专项重难点及解决措施/大树移植存活重难点及解决措施/大树移栽技术_起挖带土球.png')
    know2attach = os.path.join(KB_PATH, '建设施工技术知识/市政绿化工程施工组织/市政绿化工程专项重难点及解决措施/大树移植存活重难点及解决措施/大树移栽过程技术措施.json')
    
    json_know, info2attach, failed_paths = parse_image(image_path, know2attach, KB_PATH=KB_PATH)
 
    print(json_know)
        
        
        
        
        



